package com.friend.controller;

import com.friend.model.LoginDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

/**
 * <p></p>
 *
 * @author jiuhua.xu
 * @version 1.0
 * @since JDK 1.8
 */
@RestController
public class JdbcTokenController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    JdbcTokenStore jdbcTokenStore;

    private final static String TOKEN_URL = "http://localhost:8022/oauth/token";


    public JdbcTokenController(JdbcTokenStore jdbcTokenStore) {
        this.jdbcTokenStore = jdbcTokenStore;
    }

    @GetMapping("jdbc/token/find/{username}")
    public Object find(@PathVariable String username) {
        Collection<OAuth2AccessToken> tokens = jdbcTokenStore.findTokensByUserName(username);
        return tokens;
    }

    @PostMapping("applyToken")
    public ResponseEntity<Object> applyToken(@RequestBody LoginDTO loginDTO)  {
        System.out.println(123);

        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String,  String> body  = new LinkedMultiValueMap<>();
        body.add("grant_type","password");
        body.add("username",loginDTO.getUsername());
        body.add("password",loginDTO.getPassword());
        HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(body, headers);
//        设置restTemplate远程调用时候，对400和401不让报错，正确返回数据
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if(response.getRawStatusCode()!=400 && response.getRawStatusCode()!=401){
                    super.handleError(response);
                }
            }
        });
//         远程调用申请令牌
        ResponseEntity<Map> exchange = restTemplate.exchange(TOKEN_URL, HttpMethod.POST, httpEntity, Map.class);
        Map bodyMap = exchange.getBody();
        return ResponseEntity.ok(bodyMap);
    }

}
